import { build, loadEnv } from 'vite'
import path from 'path'
import fs from 'fs'

import buildConfig from './config/vite.build.config.ts'
import baseConfig, { ENVPREFIX } from './config/vite.base.config.ts'
import myConfig from '../vite.my.config.ts'

import { mergeObject } from '../src/utils//mergeOptions.ts'

import viteCompression from 'vite-plugin-compression'
type Algorithm = 'gzip' | 'brotliCompress' | 'deflate' | 'deflateRaw'
// https://github.com/vbenjs/vite-plugin-compression
const COMPRESSEXT = {
  gzip: '.gz',
  brotli: '.br',
}
function compressPlugin() {
  const env = loadEnv(process.env.NODE_ENV ?? 'production', process.cwd(), ENVPREFIX)
  const algorithm = env?.VITE_BUILD_COMPRESS?.split(',') ?? ['gzip', 'brotli']
  const compressPlugins: any[] = []
  algorithm.forEach(algorithm => {
    if (Object.hasOwn(COMPRESSEXT, algorithm)) {
      const option = {
        verbose: true,
        filter: /\.(js|mjs|json|css|html)$/i,
        disable: false,
        threshold: 10240, // 对大于 10KB 的文件压缩
        algorithm: algorithm as Algorithm, // @ts-ignore
        ext: COMPRESSEXT[algorithm],
        deleteOriginFile: false,
      }
      compressPlugins.push(viteCompression(option))
    }
  })
  return compressPlugins
}

const config = mergeObject(
  Object.assign(baseConfig, { build: buildConfig, plugins: compressPlugin() }),
  myConfig,
)
async function runBuild() {
  // This is use when you set postcssModule
  const cssMoudleOutDirPath = path.resolve(process.cwd(), './.css.build/')
  if (fs.existsSync(cssMoudleOutDirPath)) {
    fs.rmSync(cssMoudleOutDirPath, { recursive: true, force: true })
  }

  await build({
    configFile: false,
    ...config,
    esbuild: {
      drop: ['console', 'debugger'],
    },
  })
}

runBuild()
